const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    canvasWidth:'',
    canvasHeight:'',
    maskHidden: false,
    saveHidden: false,
    shareHidden: false,
    name: "",
    touxiang:'',
    match_image:'',    
    titleName:'',
    matchId:0,
    match_detail:'',
    match_type_list: [],
    match_content: [],
    chooseMatchTypeData:'',
    chooseMatchPriceData:0,
    isFavor:false,
    showDialog:false,
    datetimeTo: "", // 秒杀开始时间
    timeLeft:[],
    secondsTens:0,
    secondsUnits: 0,
    minutesTens: 0,
    minutesUnits: 0,
    hoursTens: 0,
    hoursUnits: 0,
    daysTens: 0,
    daysUnits: 0,
    matchMoney:0
      // 剩下的时间（天时分秒）
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    ////console.log(app.globalData.open)
   // console.log(app.globalData.user_open_id)
   console.log('-----options start------');
   console.log(options);
   console.log('------options end-----');
   var matchId = options.id;
   var shared=options.share;
   var from=options.from;
   if(from==undefined){
    this.setData({
      from:0
    })
   }else{
    this.setData({
      from:1
    })
   }
   if(shared==undefined){
      shared=0;
  }else{
     shared=1;
  }
  wx.showShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
    success(res) {
      console.log(res)
    },
    fail(e) {
      console.log(e)
    }
  })   
 this.data.matchId = matchId;
   var open=wx.getStorageSync('open');
   console.log(open);
    var id=open.id;
   if(open==undefined ){

    wx.navigateTo({
      url: '../index/login',
    })
   }
   if(open==""){

    wx.navigateTo({
      url: '../index/index',
    })
   }
  var that = this;

  let d=app.globalData;
          this.setData({
              open:open,
              platform:d.platform,    
              width:d.windowWidth,
              height:d.windowHeight,
              statusBarHeight:d.statusBarHeight,
              navHeight:d.navHeight,
              marginTop:d.navTitleTop,
              domain:d.domain,
              iUrl:d.iUrl,
              upUrl:d.upUrl
            })
    var timers=0;
    var secondsTensOld;
    var secondsUnitsOld;
    var minutesTensOld;
    var minutesUnitsOld;
    var hoursTensOld;
    var hoursUnitsOld;
    var daysTensOld;
    var daysUnitsOld;
    this.data.timer = setInterval(() => { 
      if (this.data.datetimeTo) {
        var timeLeft = util.getTimeLeft(this.data.datetimeTo);

        var secondsTens = timeLeft['secondsTens'];
        var secondsUnits = timeLeft['secondsUnits'];
        var minutesTens = timeLeft['minutesTens'];
        var minutesUnits = timeLeft['minutesUnits'];
        var hoursTens = timeLeft['hoursTens'];
        var hoursUnits = timeLeft['hoursUnits'];
        var daysTens = timeLeft['daysTens'];
        var daysUnits = timeLeft['daysUnits'];
        var leftsecond = timeLeft['leftsecond'];
        if (leftsecond > 0) {
          this.setData({
            secondsTens: secondsTens,
            secondsUnits: secondsUnits,
            minutesTens: minutesTens,
            minutesUnits: minutesUnits,
            hoursTens: hoursTens,
            hoursUnits: hoursUnits,
            daysTens: daysTens,
            daysUnits: daysUnits
          });
        } else {
          clearInterval(this.data.timer);
        }
      }
    }, 1000);
  },
  matchFavor:function(){
    var favor = this.data.isFavor;
    var that=this;
    if (favor){
     wx.showModal({
       title: '',
       content: '是否取消关注',
       success:function(res){
         if (res.confirm) {
           that.favorAction("reduce");
           that.setData({
             isFavor: !that.data.isFavor,
           })
         } 
       }
     })

    }else{
      that.favorAction("add"),
     that.setData({
        isFavor: !that.data.isFavor,
      })
    }
    
  },
favorAction:function(opitons){
  var that=this;
  var matchId=that.data.matchId;
  wx.request({
    url: 'https://lypb.com/lupao/matchfavor.php',
    data: { user_open_id: app.globalData.user_open_id,matchid:matchId,opitons:opitons},
    success:function(res){
      if(res.data){
        ////console.log(res.data)
      }
    },
    fail:function(res){

    }
  })
},
matchEnroll:function(){
     this.setData({
      showDialog: !this.data.showDialog
    });
  
},
chooseMatchType:function(option){
 this.setData({
  matchType:option.currentTarget.dataset.key,
  matchMoney: option.currentTarget.dataset.price
 })

},
matchSubmit:function(){
  var type_id=this.data.matchType;
  var match_id=this.data.matchId;
  var open=wx.getStorageSync('open');
  if(open==""){
    wx.navigateTo({
      url: '../index/index',
    })
  }
  if (!type_id){
    wx.showToast({
      title: '请选择比赛项目',
      image: '../../icon/fail.png',
      duration: 3000
    })
  }else{
    ////console.log(match_type_id)
    wx.navigateTo({
      url: "order?match_id=" + match_id + "&match_type=" + type_id,
    })
    this.setData({
      showDialog: false
    })
  }
},
  createPoster:function(){
    this.setData({
      maskHidden: !this.data.maskHidden,
    });
    var that=this;
    wx.getSystemInfo({
      success: function (res) {
       that.setData({
          canvasWidth: res.windowWidth*0.8,
          canvasHeight: res.windowHeight*0.8
        });
      }
    });
    wx.downloadFile({
      url: app.globalData.open.user_head, 
      success: function (res) {
        if (res.statusCode === 200) {

          that.setData({
            touxiang: res.tempFilePath
          })
        }
      }
    }),
      wx.downloadFile({
        url: this.data.match_detail.match_image, 
        success: function (res) {
          if (res.statusCode === 200) {
             that.setData({
              match_image: res.tempFilePath
            })
          }
        }
      }),
      wx.showToast({
        title: '生成中...',
        icon: 'loading',
        duration: 1000
      });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: true
      });
    }, 1000)

  },
  goBack:function(){
    var from=this.data.from;
      
      if(from==1){
        wx.reLaunch({
          url: '../default/index',
        })
      }else{
        wx.navigateBack();
      }
  },
  goIndex:function(){
    wx.reLaunch({
      url: '../default/index',
    })
  },
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fefefe")
    context.fillRect(0, 0, 600, 600)
    var path1 = that.data.touxiang;
    var path2 = that.data.match_image;
    var path3 = "/images/erweima.png";
    context.save(); 
    var name = app.globalData.open.user_nickname;
    context.setFontSize(17);
    context.setFillStyle('#000000');
    context.fillText(name, 255, 475);
    context.stroke();
    var len = name.replace(/[\u0391-\uFFE5]/g, "aa").length;
    var x1 = len * 8 + 255 + 10;
    //绘制一起吃面标语文字
    context.setFontSize(16);
    context.setFillStyle('#8a8a8a');
    context.fillText("正在参与", x1, 475);
    context.stroke();
    context.setFontSize(17);
    context.setFillStyle('#FF8000');
    var title=that.data.titleName;
    context.fillText(title, 255, 510);
    context.stroke();
    context.setFontSize(16);
    context.setFillStyle('#8a8a8a');
    context.fillText("识别小程序码，进入", 200, 550);
    context.stroke();
    context.setFontSize(16);
    context.setFillStyle('#8a8a8a');
    context.fillText("参与活动",430, 550);
    context.stroke();
    context.setFontSize(17);
    context.setFillStyle('#FF8000');
    context.fillText("景远路跑", 350, 550);
    context.stroke();    
    //绘制上部赛事照片
    context.drawImage(path2, 0, 0, 600,400);
    //绘制小程序码
    context.drawImage(path3, 10, 410, 160, 160);
     //绘制头像
    context.arc(220, 470, 30, 0, 2 * Math.PI) //画出圆
    context.strokeStyle = "#fefefe";
    context.clip(); //裁剪上面的圆形
    context.drawImage(path1, 190, 440, 60, 60); // 
    context.draw();
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              that.setData({
                maskHidden: true,
                shareHidden: true,
              })

            },
            fail: function () {
              that.setData({
                saveHidden:true,
              })
            }
          })
   
        },
        fail: function (res) {
          //console.log(res);
        }
      });
    }, 200);
  },
  toShare:function(){
    this.setData({
      maskHidden: false,
    })
  },
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                maskHidden: false,
                saveHidden: false,
                shareHidden: false,
              })
            }
          }, fail: function (res) {
          }
        })
      },
      fail:function(){
        wx.showModal({
          title: '重要提醒',
          content: '如需保存授权',
        })
      }
    })
  },
  searchNo:function(e){
    console.log(e);  
    var matchid=e.currentTarget.dataset.matchid;
    var matchname=e.currentTarget.dataset.matchname;
  
      wx.navigateTo({
         url: 'matchNo?match_id='+matchid+'&matchname='+matchname,
      })
    
  
  },
  searchScore:function(e){
    console.log(e);  
    var matchid=e.currentTarget.dataset.matchid;
    var matchname=e.currentTarget.dataset.matchname;
  
      wx.navigateTo({
         url: 'Score?match_id='+matchid+'&matchname='+matchname,
      })
    
  
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMatch();
  },
  getMatch(){
    let that = this;
    var url= '/wechat/Index/getMatch';
    var open = this.data.open
    var data = [];
    data['open_id'] = open.id;
    data['match_id'] = this.data.matchId;
    data['from'] = 'index';
    var type = 'get';
  app.request(url,data,type).then(res=>{ 
      // console.log(11); 
       console.log(res);
       that.setData({
           match:res.match,
           type:res.type

       })
     //  that.wxUpdate(); //that.wxLogIn();  
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var match_id=this.data.matchId
    var matchname=this.data.matchName;
    var title=this.data.matchName;
    　　var shareObj = {
      　　　　title: title,    
      　　　　 path: '/pages/match/match?match_id=' + this.data.matchId  + "&matchname="+this.data.matchName+"&share=5", 
      　　　
      　　}
      　　if( e.from == 'button' ){
        　　　shareObj.title=title;
      　　　　shareObj.path = '/pages/match/match?match_id=' + this.data.matchId  + "&matchname="+this.data.matchName+"&share=5"
      　　}
      console.log(shareObj);
      console.log('onShareApp');
     
     // this.setShare(2,'index',md5);
     
      　　// 返回shareObj
      　　return shareObj;
  },
   //分享朋友圈
  onShareTimeline(){
    // console.log(e);
    var match_id=this.data.matchId
    var matchname=this.data.matchName;
    var title=this.data.matchName;
     this.setData({
       share:true
     });
     return{
       title: title,    
            
       query: 'match_id='+match_id+'&matchname='+matchname+"&share=5",        
       //imageUrl:'https://wl.browin.net.cn/static/wechat/ad1.png'      
       }
   },
   shareLine:function(e){
     
     this.setData({
   
       share:true
     })
   },
   hiddenShare:function(){
     this.setData({
       share:false
     })
   },
})